package com.alan.controller;

import com.alan.repository.AdminRepository;
import com.alan.repository.impl.AdminRepsitoryImpl;
import com.alan.repository.impl.StudentRepositoryImpl;
import com.alan.repository.impl.TeacherRepositoryImpl;
import com.alan.service.RegisterService;
import com.alan.service.impl.RegisterServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/newpassword")
public class LoginSetPasswordServlet extends HttpServlet {
    private RegisterService registerService = new RegisterServiceImpl();
    private StudentRepositoryImpl studentRepository = new StudentRepositoryImpl();
    private TeacherRepositoryImpl teacherRepository = new TeacherRepositoryImpl();
    private AdminRepository adminRepository = new AdminRepsitoryImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String tclass = req.getParameter("tclass");
        String identify = req.getParameter("identify");
        String re = registerService.find(username, identify);
        if (re == "null") {
            req.setAttribute("info", "nohaved");
            req.getRequestDispatcher("fail.jsp").forward(req, resp);
        } else {
            switch (identify) {
                case "student":
                    studentRepository.change(username, password);
                    break;
                case "teacher":
                    teacherRepository.newpassword(username, tclass, password);
                    break;
                case "admin":
                    adminRepository.newpassword(username, password);
                    break;
            }
            req.getRequestDispatcher("success.jsp?info=setnew").forward(req, resp);
        }
    }
}
